import React, { Component } from 'react'
import errorImage from '@/assets/error.png'

import {
  Card,
  Breadcrumb,
  Form,
  Radio,
  Select,
  DatePicker,
  Button,
  Table,
  Image,
  Space,
  Tag,
  Modal,
  message
} from 'antd'

import { EditOutlined, DeleteOutlined } from '@ant-design/icons' // edit 和 delete

import { getAllChanges } from '@/api/channels.js'
import { getArticles, delArticle } from '@/api/article'

const { Option } = Select
const { RangePicker } = DatePicker
const { confirm } = Modal



const articleStatus = {
  0: { text: '草稿', color: 'grey' },
  1: { text: '待审核', color: 'lime' },
  2: { text: '审核通过', color: 'green' },
  3: { text: '审核失败', color: 'red' },
}

export default class ArticleList extends Component {
  columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      width: 200,
      render: data => {
        if (data.type === 0) {
          return <Image src={errorImage} />
        } else {
          return <Image src={data.images[0]} />
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: data => {
        const tagObj = articleStatus[data]
        return <Tag color={tagObj.color}>{tagObj.text}</Tag>
      },
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space>
            <Button 
            type="primary"
             shape="circle" 
             icon={<EditOutlined />} 
             onClick={()=>{
               this.props.history.push(`/home/articlepublish/${data.id}`)
             }}
             ></Button>
            <Button 
            type="primary" 
            shape="circle" 
            danger 
            icon={<DeleteOutlined />}
            onClick={()=>this.handleDel(data.id)}
            ></Button>
          </Space>
        )
      },
    },
  ]
  state = {
    changes: [],
    // 文章用的
    articles: [], // 文章数据
    currentPage: 1, // 当前页
    pageSize: 10, // 每页条数
    total: 0, // 总条数
    isLoading: false,
  }

  async getAllChanges() {
    const {
      data: { data },
    } = await getAllChanges()
    // console.log(data.channels);
    this.setState({
      changes: data.channels,
    })
  }

  async getArticles() {
    this.setState({
      isLoading: true,
    })
    const {
      data: { data },
    } = await getArticles({
      page: this.state.currentPage,
      per_page: this.state.pageSize,
      ...this.params,
    })
    // console.log(data);
    // 全留着都有用
    this.setState({
      articles: data.results,
      currentPage: data.page,
      pageSize: data.per_page,
      total: data.total_count,
      isLoading: false,
    })
  }
  componentDidMount() {
    this.getAllChanges()
    this.getArticles()
  }

  // 把4个参数搜集到params里面
  params = {}
  // 点击筛选 时间的处理
  onFinish = values => {
    const { status, channel_id, date } = values
    // 添加 状态
    this.params.status = status
    // 添加频道id
    this.params.channel_id = channel_id
    // 收集时间

    if (values.date) {
      this.params.begin_pubdate =
        values.date && date[0].startOf('day').format('YYYY-MM-DD hh-mm-ss')
      this.params.end_pubdate = values.date && date[1].endOf('day').format('YYYY-MM_DD hh-mm-ss')
    }

    this.setState(
      {
        currentPage: 1,
      },
      () => {
        // 发送网请
        this.getArticles()
      }
    )
  }

  // 操作中 删除按钮的处理
  handleDel = (id) => {
    confirm({
      title: '温馨提示?',
      content: '你确定要删除?',
      onOk: async() => {
        try{
          await delArticle(id)

          this.getArticles()
          message.success('恭喜, 删除成功~')

        }catch(error) {
          message.error('删除失败')
        }
      },
    });
  }

  render() {
    return (
      <div className="articleList">
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item href="/home">首页</Breadcrumb.Item>
              <Breadcrumb.Item>文章列表</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          {/*  card 的内容  */}
          {/* 其中的一个默认值 */}
          <Form initialValues={{ status: undefined }} onFinish={this.onFinish}>
            {/* status 是看接口需要的才写的 */}
            <Form.Item label="状态" name="status">
              <Radio.Group>
                <Radio value={undefined}>全部</Radio>
                <Radio value={0}>草稿</Radio>
                <Radio value={1}>待审核</Radio>
                <Radio value={2}>审核通过</Radio>
                <Radio value={3}>审核失败</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="频道" name="channel_id">
              <Select placeholder="请选择频道" style={{ width: 200 }}>
                {this.state.changes.map(item => (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="日期" name="password">
              <RangePicker />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>

        {/* 筛选卡片 */}

        <Card title={`根据条件筛选数据 共筛选出${this.state.total}条`}>
          <Table
            rowKey="id"
            loading={this.state.isLoading}
            pagination={{
              position: ['bottomCenter'],
              current: this.state.currentPage,
              pageSize: this.state.pageSize,
              total: this.state.total,
              onChange: (page, pageSize) => {
                this.setState(
                  {
                    currentPage: page,
                    pageSize,
                    articles: [],
                  },
                  () => {
                    this.getArticles()
                  }
                )
              },
            }}
            columns={this.columns}
            dataSource={this.state.articles}
          />
        </Card>
      </div>
    )
  }
}
